package com.jinx.config;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.UUIDGenerator;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

import java.io.Serializable;
import java.util.Optional;
import java.util.Random;

/**
 * @author Jinx
 * @date 2021/7/26 12:42 上午
 */
@Configuration
@EnableJpaAuditing
public class JpaConfig implements AuditorAware<String>, IdentifierGenerator {

    private final Random random = new Random();

    @Override
    public Optional<String> getCurrentAuditor() {
        return Optional.of("jinx");
    }

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        System.out.println("session = " + session);
        System.out.println("object = " + object);
        return this.idGenerate();
    }


    private String idGenerate(){
        StringBuilder sb = new StringBuilder(String.valueOf(System.currentTimeMillis()));
        for (int i = sb.length(); i < 19; i++) {
            sb.append(random.nextInt(10));
        }

        return sb.toString();
    }
}
